using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace FreeFlow.Administration
{
	/// <summary>
	/// A collection of folders.
	/// </summary> 
	public sealed class FolderCollection : DatabaseAware, IRefreshable, IList, IBindingList, IEnumerable<Folder>
	{
    private List<Folder> folderList;
    private Map map;
    private string stageName;
    private string parentFolderId;
    private string whereClause;

    /// <summary>
    /// Initializes a new instance of the <see cref="FolderCollection"/> class using the specified SQL WHERE clause.
    /// </summary>
    /// <param name="whereClause">The where clause.</param>
    /// <param name="server">The server.</param>
    public FolderCollection(string whereClause, Server server) : base(server)
    {
      this.whereClause = whereClause; 
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="FolderCollection"/> class for the specified map.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="map">The map.</param>
		public FolderCollection(Server server, Map map) : base(server)
		{
      this.map = map;
		}

    /// <summary>
    /// Initializes a new instance of the <see cref="FolderCollection"/> class for the specifed stage in the specified map.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="map">The map.</param>
    /// <param name="stageName">Name of the stage.</param>
    public FolderCollection(Server server, Map map, string stageName) : base(server)
    {
      this.map = map;
      this.stageName = stageName;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="FolderCollection"/> class for the specified parent folder ID.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="parentFolderId">The parent folder ID.</param>
    public FolderCollection(Server server, string parentFolderId) : base(server)
    {
      this.parentFolderId = parentFolderId;
    }

    private void LoadFromQuery(string query)
    {
      List<string> folderIDs = new List<string>();
      using (IDataReader reader = Server.ExecuteReader(query))
      {
        while (reader.Read()) 
        {
          folderIDs.Add(reader["eFolderID"].ToString());
        }
      }

      for (int i = 0; i < folderIDs.Count; i++)
      {
        Folder folder = new Folder(Server, folderIDs[i].ToString());
        folderList.Add(folder);
      }
    }

    private void ReadFolders()
    {
      if (folderList == null)
      {
        folderList = new List<Folder>();

        if (parentFolderId != null)
        {
          // parent folder ID
          LoadFromQuery(string.Format("SELECT eFolderID FROM eFolder WHERE eParent='{0}' ORDER BY eFolderName", 
            parentFolderId));
        }
        else if (whereClause != null)
        {
          LoadFromQuery(string.Format("SELECT eFolderID FROM eFolder WHERE {0}", whereClause));
        }
        else
        {
          // maps and stages can be more efficient, do in one query
          string stageWhereClause = string.Empty;
          if (stageName != null)
            stageWhereClause = string.Format("AND eStageName = '{0}'", SqlEscape(stageName));

          string sql = string.Format("SELECT * FROM eFolder, {0} WHERE eMapName = '{1}' {2} AND eFolder.EFOLDERID = {0}.eFolderID ORDER BY eFolderName", 
            map.TableName, map.Name, stageWhereClause);
          if (Server.DatabaseType == DatabaseType.SqlServer)
            sql = string.Format("SELECT * FROM eFolder WITH (NOLOCK), {0} WITH (NOLOCK) WHERE eMapName = '{1}' {2} AND eFolder.EFOLDERID = {0}.eFolderID ORDER BY eFolderName",
              map.TableName, map.Name, stageWhereClause);

          using (IDataReader reader = Server.ExecuteReader(sql))
          {
            while (reader.Read()) 
            {
              Folder folder = new Folder(Server, reader);
              folderList.Add(folder);
            }
          }
        }
      }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      ReadFolders();
      return folderList.GetEnumerator();
    }

    #region IEnumerable<Folder> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<Folder> GetEnumerator()
    {
      ReadFolders();
      return folderList.GetEnumerator();
    }

    #endregion

    private int count = -1;
    private void ReadCount()
    {
      if (parentFolderId != null)
      {
        count = Convert.ToInt32(Server.ExecuteScalar(
          string.Format("SELECT COUNT(*) FROM eFolder WHERE eParent='{0}'", parentFolderId)));
      }
      else if (whereClause != null)
      {
        count = Convert.ToInt32(Server.ExecuteScalar(
          string.Format("SELECT COUNT(*) FROM eFolder WHERE {0}", whereClause)));
      }
      else
      {
        string stageWhereClause = string.Empty;
        if (stageName != null)
          stageWhereClause = string.Format("AND eStageName = '{0}'", SqlEscape(stageName));

        string sql = string.Format("SELECT COUNT(*) FROM eFolder WHERE eMapName = '{1}' {2}", map.TableName, map.Name, stageWhereClause);
        if (Server.DatabaseType == DatabaseType.SqlServer)
          sql = string.Format("SELECT COUNT(*) FROM eFolder WITH (NOLOCK) WHERE eMapName = '{1}' {2}", map.TableName, map.Name, stageWhereClause);

        count = Convert.ToInt32(Server.ExecuteScalar(sql));
      }
    }

    /// <summary>
    /// Gets the number of folders in this collection.
    /// </summary>
    public int Count
    {
      get
      {
        if (folderList == null)
        {
          if (count == -1)
            ReadCount();
          return count;
        }
        else
          return folderList.Count;
      }
    }

    /// <summary>
    /// Gets the <see cref="Folder"/> at the specified index.
    /// </summary>
    public Folder this[int index]
    {
      get
      {
        ReadFolders();
        return (Folder)folderList[index];
      }
    }

    #region IRefreshable Members

    /// <summary>
    /// Refreshes this instance.
    /// </summary>
    public void Refresh()
    {
      folderList = null;
      count = -1;
    }

    #endregion
    #region IList Members

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> is read-only.
    /// </summary>
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }

    object IList.this[int index]
    {
      get
      {
        ReadFolders();
        if ((index >= 0) && (index < Count))
          return folderList[index];
        return null;
      }
      set
      {
        throw new NotSupportedException(readOnlyListMessage);
      }
    }

    /// <summary>
    /// Removes the <see cref="T:System.Collections.IList"/>
    /// item at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index of the item to remove.</param>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>.</exception>
    /// <exception cref="T:System.NotSupportedException">
    /// 	<para>The <see cref="T:System.Collections.IList"/> is read-only.</para>
    /// 	<para>-or-</para>
    /// 	<para>The <see cref="T:System.Collections.IList"/> has a fixed size.</para>
    /// </exception>
    public void RemoveAt(int index)
    {
      ReadFolders();
      Folder folder = folderList[index];
      Remove(folder);
    }

    void IList.Insert(int index, object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Removes the specified folder from the database.
    /// </summary>
    /// <param name="folder">The folder to remove.</param>
    public void Remove(Folder folder)
    {
      ReadFolders();
      if (folderList.Contains(folder))
      {
        folder.Delete();
        folderList.Remove(folder);
      }
    }

    void IList.Remove(object value)
    {
      Remove((Folder)value);
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// 	<see langword="true"/> if the <see cref="T:System.Object"/>
    /// is found in the <see cref="T:System.Collections.IList"/>; otherwise, <see langword="false"/>.
    /// </returns>
    public bool Contains(object value)
    {
      ReadFolders();
      return folderList.Contains((Folder)value);
    }

    void IList.Clear()
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Determines the index of a
    /// specific item in the <see cref="T:System.Collections.IList"/>.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// The index of <paramref name="value"/> if found in the list; otherwise, -1.
    /// </returns>
    public int IndexOf(object value)
    {
      ReadFolders();
      return folderList.IndexOf((Folder)value);
    }

    int IList.Add(object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </summary>
    public bool IsFixedSize
    {
      get
      {
        return true;
      }
    }

    #endregion
    #region ICollection Members

    /// <summary>
    /// Gets a value
    /// indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized
    /// (thread-safe).
    /// </summary>
    public bool IsSynchronized
    {
      get
      {
        return false;
      }
    }

    /// <summary>
    /// Copies the elements of
    /// the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is <see langword="null"/>.</exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.</exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<para>
    /// 		<paramref name="array"/> is multidimensional.</para>
    /// 	<para>-or-</para>
    /// 	<para>
    /// 		<paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.</para>
    /// 	<para>-or-</para>
    /// 	<para>The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.</para>
    /// </exception>
    /// <exception cref="T:System.InvalidCastException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
    public void CopyTo(Folder[] array, int index)
    {
      ReadFolders();
      folderList.CopyTo(array, index);
    }

    void ICollection.CopyTo(Array array, int index)
    {
      CopyTo((Folder[])array, index);
    }

    /// <summary>
    /// Gets an object that
    /// can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
    /// </summary>
    public object SyncRoot
    {
      get
      {
        return null;
      }
    }

    #endregion
    #region IBindingList Members

    void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
      ReadFolders();
      sortProperty = property;
      sortDirection = direction;
      folderList.Sort(new Comparer<Folder>(sortProperty, sortDirection));
    }

    private PropertyDescriptor sortProperty;
    PropertyDescriptor IBindingList.SortProperty
    {
      get
      {
        return sortProperty;
      }
    }

    bool IBindingList.SupportsSorting
    {
      get
      {
        return true;
      }
    }

    bool IBindingList.IsSorted
    {
      get
      {
        return (sortProperty != null);
      }
    }

    void IBindingList.RemoveSort()
    {
      sortProperty = null;
    }

    private ListSortDirection sortDirection;
    ListSortDirection IBindingList.SortDirection
    {
      get
      {
        return sortDirection;
      }
    }

    #region not implemented 
    int IBindingList.Find(PropertyDescriptor property, object key)
    {
      return 0;
    }

    bool IBindingList.AllowRemove
    {
      get
      {
        return false;
      }
    }

    bool IBindingList.SupportsSearching
    {
      get
      {
        return false;
      }
    }

    private ListChangedEventHandler listChanged;
    event ListChangedEventHandler IBindingList.ListChanged
    {
      add { listChanged += value; }
      remove { listChanged -= value; }

    }

    bool IBindingList.SupportsChangeNotification
    {
      get
      {
        return false;
      }
    }

    object IBindingList.AddNew()
    {
      return null;
    }

    bool IBindingList.AllowEdit
    {
      get
      {
        return false;
      }
    }

    void IBindingList.RemoveIndex(PropertyDescriptor property)
    {
    }

    void IBindingList.AddIndex(PropertyDescriptor property)
    {
    }

    bool IBindingList.AllowNew
    {
      get
      {
        return false;
      }
    }

    #endregion
    #endregion
  }
}
